<?php

Yii::import('application.extensions.taging.TagBase', true);
/*
 * Insert related tags
 * Delete related tags
 * 
 * Add to model that uses tags eg. Portfolio
 *  public function behaviors(){
  return array('TagBehavior' => array(
  'class' => 'application.extentions.taging.TagBehavior',
  'tagTable'=>  'tag' //tag model name
  ));
  }
 * 
 */

/**
 * Description of TagBehavior
 *
 * @author sadaf.siddiqui
 */
class TagBehavior extends TagBase {

    private $newTags = array();
    private $relatedTags = array();

    // After the save process of the model this behavior is attached to 
    // is finished, we begin saving our MANY_MANY related data 
    public function afterSave($event) {
        if (!is_array($this->ignoreRelations))
            throw new CException('ignoreRelations of CAdvancedArBehavior needs to be an array');

        $this->writeTags();
        parent::afterSave($event);
        return true;
    }

    protected function writeTags() {
        if ($this->trace)
            Yii::trace('writing Tags data for ' . get_class($this->owner), 'system.db.ar.CActiveRecord');

        if ($this->owner->assigntags) {

            $tagsarray = explode(",", $this->owner->assigntags);

            $this->newTags = $this->makeRelatedTagArray($tagsarray);

            if (count($this->newTags) > 0) {

                //add new tags  
                $this->execute($this->addTags(implode("'),('", $this->newTags)));
                $tags = $this->fetchAll($this->newTags);
                foreach ($tags as $tag)
                    $this->relatedTags[] = "(" . $tag['id'] . "," . $this->owner->id . ")";
            }
            $this->execute($this->clearTags($this->owner->id));
            $this->execute($this->addRelatedTags($this->relatedTags));
        }
    }

    protected function makeRelatedTagArray($tagsArray) {
        $tags = $tagsArray;

        $existtag = $this->fetchAll($tags);

        foreach ($existtag as $et) {
            $key = array_search($et['name'], $tags);

            if (!($key === NULL)) {

                $this->relatedTags[] = "(" . $et['id'] . "," . $this->owner->id . ")";
                unset($tags[$key]);
            }
        }
        return $tags;
    }

    public function retriveTags() {

        return $this->fetchRelatedTagsCommaSeperated($this->owner->id);
    }

    public function afterFind($event) {

        $this->owner->assigntags = $this->retriveTags();
        parent::afterFind($event);
        return true;
    }

}

?>
